// pages/login/login.js
import request from '../../utils/request';

Page({
  onGetPhoneNumber(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      wx.showLoading({
        title: '正在登录...',
      });
      wx.login({
        success: (res) => {
          if (res.code) {
            wx.request({
              url: 'http://localhost:8090/xh/wechat/login',
              method: 'POST',
              header: {
                'Content-Type': 'application/json'
              },
              data: {
                code: res.code,
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv
              },
              success: (loginRes) => {
                wx.hideLoading();
                if (loginRes.data.code === 200) {
                  const token = loginRes.data.data.token;
                  wx.setStorageSync('token', token);
                  wx.showToast({
                    title: '登录成功',
                    icon:'success'
                  });
                  wx.switchTab({
                    url: '/pages/my/my'
                  });
                } else {
                  wx.showToast({
                    title: loginRes.data.message,
                    icon: 'none'
                  });
                }
              },
              fail: () => {
                wx.hideLoading();
                wx.showToast({
                  title: '网络请求失败',
                  icon: 'none'
                });
              }
            });
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '获取登录凭证失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          wx.hideLoading();
          wx.showToast({
            title: '获取登录凭证失败',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '用户拒绝授权手机号',
        icon: 'none'
      });
    }
  }
});